﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
using System.Xml;

namespace Kkc.Application.Helpers
{
    public sealed class SyndicationFeedResult: ActionResult
    {
        private readonly SyndicationFeedFormatter syndicationFeedFormatter;

        public SyndicationFeedResult(SyndicationFeedFormatter syndicationFeedFormatter)
        {
            if (syndicationFeedFormatter == null)
                throw new ArgumentNullException("syndicationFeedFormatter");

            this.syndicationFeedFormatter = syndicationFeedFormatter;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();

            if (syndicationFeedFormatter is Rss20FeedFormatter)
            {
                context.HttpContext.Response.ContentType = "application/rss+xml";
            }
            else if (syndicationFeedFormatter is Atom10FeedFormatter)
            {
                context.HttpContext.Response.ContentType = "application/atom+xml";
            }
            else
            {
                throw new NotSupportedException();
            }

            using (var xmlWriter = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                syndicationFeedFormatter.WriteTo(xmlWriter);
            }
        }
    }
}